package com.jade.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CqUtil {
	
	public static HashMap<String,String> FileChat = new HashMap<String,String>();
	public static HashMap<String,List<Map>> DataChat = new HashMap<String,List<Map>>();
	
	public static String Read(String Path){
		  StringBuffer sb = new StringBuffer();
		  BufferedReader Br = null;
		  String   line   =   null; 
		  if(FileChat.get(Path)!=null){
			  return FileChat.get(Path);
		    }
		  try {
			  File file = new File(Path);
			  if(file.exists()){
			     Br = new BufferedReader(new InputStreamReader(new FileInputStream(Path),"UTF-8"));   
	           while((line = Br.readLine())!=null)   
	           {   
	      	     sb.append("\n").append(line);
	           }
			  }
		  }catch (Exception e) {
				System.out.print("WriteText"+e.toString());
		  }finally{
				if(Br!=null)
					try {
						Br.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		  line = sb.toString();
		  if(line.length()>1){
			  FileChat.put(Path, line.substring(1));
		     return line.substring(1);
		  }else
		     return "";
	}
	
	public static void Write(String Text,String Path,String FileName) {
		  BufferedWriter bw = null;
		try {
			    String FilePathStr = Path;
			    if(FileName!=null){//路径不包含文件名
			    	File FilePath = new File(Path);
			        if (!FilePath.exists()) FilePath.mkdirs(); //创建路径
			    	FilePathStr = Path+"/"+FileName;
			    }else{//路径包含文件名
			    	FilePathStr = Path.substring(0,Path.lastIndexOf("/"));
			    	File FilePath = new File(FilePathStr);
			        if (!FilePath.exists()) FilePath.mkdirs(); //创建路径
			        FilePathStr = Path;
			    }
			    //变更缓存
			    if(FileChat.get(FilePathStr)!=null){
			    	FileChat.remove(FilePathStr);
			    }
				bw =  new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(FilePathStr), "UTF-8"));
			    bw.write(Text);
			    bw.close();
			} catch (Exception e) {
				System.out.print("WriteText"+e.toString());
			}finally{
				if(bw!=null)
					try {
						bw.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
	}
	
	public static String formatDate(Date date, String disply) {
		  try {
	  if (date == null) {
	    return null;
	  }
	  String format = "yyyy-MM-dd HH:mm:ss";
	  if (disply.equalsIgnoreCase("long")) {
	    format = "yyyy-MM-dd HH:mm:ss";
	  }
	  else if (disply.equalsIgnoreCase("short")) {
	    format = "yyyy-MM-dd";
	  }
	  else if (disply.equalsIgnoreCase("year")) {
	    format = "yyyy";
	  }
	  else if (disply.equalsIgnoreCase("month")) {
	    format = "MM";
	  }
	  else if (disply.equalsIgnoreCase("day")) {
	    format = "dd";
	  }
	  else if (disply.equalsIgnoreCase("time")) {
	    format = "HH:mm:ss";
	  }else{
	    format=disply;
	  }
	  SimpleDateFormat dateFormat = new SimpleDateFormat(format);

	  return dateFormat.format(date).toString();
		  }catch (Exception e) {
			  System.out.println("util.TimeKit>>>>>>"+e.toString());
	  }
	  return "";
	}
	
	/**
	 * 使含有汉字的字符正常显示汉字
	 * @param strToTrans
	 * @return
	 */
	public static String getGBString(String strToTrans) {
	  if (strToTrans == null || strToTrans.trim().length() == 0) {
	    return null;
	  }
	  try {
	    return new String(strToTrans.getBytes("ISO-8859-1"), "UTF-8");
	  }
	  catch (UnsupportedEncodingException ex) {
	    System.out.println("StringKit.getGBString()  wrong" + ex.getMessage());
	  }
	  return null;
	}
	
	public static String getIpAddr(HttpServletRequest request) {
		  String ip = request.getHeader("x-forwarded-for");     
		  if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
		    ip = request.getHeader("Proxy-Client-IP");     
		  }     
		  if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
		    ip = request.getHeader("WL-Proxy-Client-IP");     
		  }     
		  if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {     
		    ip = request.getRemoteAddr();     
		  }     
		  return ip;     
	}
	
	public static String now(String disply) {
		  try {
	  String format = "yyyy-MM-dd HH:mm:ss";
	  if (disply.equalsIgnoreCase("long")) {
	    format = "yyyy-MM-dd HH:mm:ss";
	  }
	  else if (disply.equalsIgnoreCase("short")) {
	    format = "yyyy-MM-dd";
	  }
	  else if (disply.equalsIgnoreCase("year")) {
	    format = "yyyy";
	  }
	  else if (disply.equalsIgnoreCase("month")) {
	    format = "MM";
	  }
	  else if (disply.equalsIgnoreCase("day")) {
	    format = "dd";
	  }
	  else if (disply.equalsIgnoreCase("time")) {
	    format = "HH:mm:ss";
	  }else if(disply.equalsIgnoreCase("yearmonth")) {
	    format = "yyyyMM";
	  }else {
	   format =disply;
	  }
	  Date date = new Date();
	  SimpleDateFormat dateFormat = new SimpleDateFormat(format);
	  return dateFormat.format(date).toString();
		}catch (Exception e) {
			System.out.println(e.getMessage());
	  }
		return "";
	}
	/*  Description: 处理 String.replaceAll(string,string)中，第一个字符参数，使的字符里面的一些正则表达式特殊字符能正常化使用
	 *  @param1:  String s  待处理字符串  　　
	 *  return    String　处理后的字符串
	 */
	public static String quote(String s) {
	  int slashEIndex = s.indexOf("\\E");
	  if (slashEIndex == -1) {
	    return "\\Q" + s + "\\E";
	  }
	  StringBuffer sb = new StringBuffer(s.length() * 2);
	  sb.append("\\Q");
	  slashEIndex = 0;
	  int current = 0;
	  while ( (slashEIndex = s.indexOf("\\E", current)) != -1) {
	    sb.append(s.substring(current, slashEIndex));
	    current = slashEIndex + 2;
	    sb.append("\\E\\\\E\\Q");
	  }
	  sb.append(s.substring(current, s.length()));
	  sb.append("\\E");
	  return sb.toString();
	}

	/*  Description: 处理 String.replaceAll(string,string)中，第二个字符参数，使的字符里面的一些正则表达式特殊字符能正常化使用
	 *  @param1:  String s  待处理字符串  　　
	 *  return    String　处理后的字符串
	 */
	public static String quoteReplacement(String s) {
	  if ( (s.indexOf('\\') == -1) && (s.indexOf('$') == -1)) {
	    return s;
	  }
	  StringBuffer sb = new StringBuffer();
	  for (int i = 0; i < s.length(); i++) {
	    char c = s.charAt(i);
	    if (c == '\\') {
	      sb.append('\\');
	      sb.append('\\');
	    }
	    else if (c == '$') {
	      sb.append('\\');
	      sb.append('$');
	    }
	    else {
	      sb.append(c);
	    }
	  }
	  return sb.toString();
	}
	
	public static boolean isNumeric(String str){
		  if(str==null || "".equals(str))
			  return false;
	      Pattern pattern = Pattern.compile("[0-9]*");
	      Matcher isNum = pattern.matcher(str);
	      if( !isNum.matches() ){
	          return false;
	      }
	          return true;
	  }
	
	public static Date getDateTimeByString(String date,String format) {
		  SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				  format);
	  try {
	    return simpleDateFormat.parse(date);
	  }
	  catch (Exception e) {
	  	System.out.println("util.TimeKit>>>>>>"+e.toString());
	  }
	  return null;
	}
	
	public static String clearHTML(String htmlStr){
		  if (htmlStr == null){   
	        return "";   
	    }
	    if("".equals(htmlStr.trim())){
	    	 return ""; 
	    }
	    htmlStr = htmlStr.trim();
	    htmlStr = htmlStr.replaceAll("\\Q \\E",""); 
	    htmlStr = htmlStr.replaceAll("\\Q\t\\E","");
	    htmlStr = htmlStr.replaceAll("\\Q\r\\E","");
	    htmlStr = htmlStr.replaceAll("\\Q\n\\E","");
	    htmlStr = htmlStr.replaceAll("\\Q/*\\E","*"); 
	    htmlStr = htmlStr.replaceAll("\\Q*/\\E","*"); 
	    htmlStr = htmlStr.replaceAll("(\\w:){0,1}(\\*\\w+)*(\\.){0,1}\\w*\\*{0,1}\\{.*?\\}","");//替换WORD样式
	    htmlStr = htmlStr.replaceAll("\\&[a-zA-Z]{1,10};","").replaceAll("<[^>]*>","");//替换HTML格式
	    htmlStr = htmlStr.replaceAll("[(/>)<]","");//替换html样式
	    //去除零字节字符
	    return replaceAllErroAsc(htmlStr); 
	}
	
	public static String replaceAllErroAsc(String str){
		if(str==null){
			return null;
		}
		int ascNum=0;
		char erroChar=(char)ascNum;
		String returnString=str;
		String erroString=String.valueOf(erroChar);
		while(returnString.indexOf(erroString)>=0 & ascNum<10000){    		
			returnString=str.substring(0,str.indexOf(erroString));
			if((str.indexOf(erroString)+1)<str.length()){
				returnString+=str.substring(str.indexOf(erroString)+1);
			}
			str = returnString;
			ascNum++;
		}
		return returnString;
	}
	
	public static String toHTML(String in) {
	    StringBuffer out = new StringBuffer();
	    for (int i = 0; in != null && i < in.length(); i++) {
	      char c = in.charAt(i);
	      if (c == '\'') {
	        out.append("&#039;");
	      }
	      else if (c == '\"') {
	        out.append("&#034;");
	      }
	      else if (c == '<') {
	        out.append("&lt;");
	      }
	      else if (c == '>') {
	        out.append("&gt;");
	      }
	      else if (c == '&') {
	        out.append("&amp;");
	      }
	      else if (c == ' ') {
	        out.append("&nbsp;");
	      }
	      else if (c == '\n') {
	        out.append("<br/>");
	      }
	      else {
	        out.append(c);
	      }
	    }
	    return out.toString();
	  }
}